package controller

import (
	"SE/Response"
	"SE/model"
	"SE/service"
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
)

type PController struct {
	pService *service.PService
}

func NewPController(pService *service.PService) *PController {
	return &PController{pService: pService}
}

func (pc *PController) PList(c *gin.Context) {
	id := c.Query("id")
	Ps, err := pc.pService.GetP(id)
	if err != nil {
		Response.Err(c, 400, "查询失败", err)
		return
	}
	c.JSON(http.StatusOK, Ps)
}

func (pc *PController) AddP(c *gin.Context) {
	var newP model.P
	newP.Name = c.Query("name")
	newP.Location = c.Query("location")
	newP.Status, _ = strconv.Atoi(c.Query("status"))
	newP.Total, _ = strconv.Atoi(c.Query("total"))
	newP.Kind, _ = strconv.Atoi(c.Query("kind"))
	newP.Latitude, _ = strconv.ParseFloat(c.Query("latitude"), 64)
	newP.Longitude, _ = strconv.ParseFloat(c.Query("longitude"), 64)
	newP.MId, _ = strconv.Atoi(c.Query("mid"))
	newP.CarNum, _ = strconv.Atoi(c.Query("car_num"))

	if err := pc.pService.AddP(newP); err != nil {
		Response.Err(c, 400, "添加失败", err)
		return
	}

	Response.Success(c, 200, "success", nil)
}

func (pc *PController) GetAllP(c *gin.Context) {
	Ps, err := pc.pService.GetAllP()
	if err != nil {
		Response.Err(c, 400, "查询失败", err)
		return
	}
	c.JSON(http.StatusOK, Ps)
}

func (pc *PController) UpdateP(c *gin.Context) {
	var newP model.P
	ids, _ := strconv.Atoi(c.Query("id"))
	newP.Id = int64(ids)
	newP.MId, _ = strconv.Atoi(c.Query("mid"))
	newP.Status, _ = strconv.Atoi(c.Query("status"))
	newP.CarNum, _ = strconv.Atoi(c.Query("car_num"))
	newP.Name = c.Query("name")
	newP.Location = c.Query("location")
	newP.Kind, _ = strconv.Atoi(c.Query("kind"))
	newP.Latitude, _ = strconv.ParseFloat(c.Query("latitude"), 64)
	newP.Longitude, _ = strconv.ParseFloat(c.Query("longitude"), 64)
	newP.Total, _ = strconv.Atoi(c.Query("total"))

	fmt.Println(newP)

	err := pc.pService.UpdateP(newP)
	if err != nil {
		Response.Err(c, 400, "更新失败", err)
		return
	}
	Response.Success(c, 200, "success", nil)
}

func (pc *PController) GetMyp(c *gin.Context) {
	mid, _ := strconv.Atoi(c.Query("mid"))
	Ps, err := pc.pService.GetMyp(mid)
	if err != nil {
		Response.Err(c, 400, "查询失败", err)
		return
	}
	Response.Success(c, 200, "success", Ps)
}
